/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function (nums) {
  let res = []
  nums.sort((a, b) => a - b)
  for (let i = 0; i < nums.length - 2; i++) {
    if (nums[i] > 0) break
    if (i > 0 && nums[i - 1] == nums[i]) i++
    let left = i + 1,
      right = nums.length
    while (left < right) {
      if (nums[i] + nums[left] + nums[right] == 0) {
        res.push([nums[i], nums[left], nums[right]])
        left++
        while (left < right && nums[left] == nums[left - 1]) left++
        right--
        while (left < right && nums[right] == nums[right + 1]) right--
      } else if (nums[i] + nums[left] + nums[right] < 0) {
        left++
        while (left < right && nums[left] == nums[left - 1]) left++
      } else {
        right--
        while (left < right && nums[right] == nums[right + 1]) right--
      }
    }
  }
  return res
}

threeSum([-1, 0, 1, 2, -1, -4])
